use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::sessions::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub user_id: Option<String>,
    pub ip_address: Option<String>,
    pub user_agent: Option<String>,
    pub payload: String,
    pub last_activity: i32,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Payload must not be empty."))]
    pub payload: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            payload: self.payload.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::sessions::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a session by the provided id
    ///
    /// # Errors
    ///
    /// When could not find session or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let session = sessions::Entity::find()
            .filter(
                model::query::condition()
                    .eq(sessions::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        session.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds sessions by the provided user id
    ///
    /// # Errors
    ///
    /// When could not find sessions or DB query error
    pub async fn find_by_user_id(db: &DatabaseConnection, user_id: &str) -> ModelResult<Vec<Self>> {
        let sessions = sessions::Entity::find()
            .filter(
                model::query::condition()
                    .eq(sessions::Column::UserId, user_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(sessions)
    }

    /// Asynchronously creates a session and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the session into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let session = sessions::ActiveModel {
            user_id: ActiveValue::set(params.user_id.clone()),
            ip_address: ActiveValue::set(params.ip_address.clone()),
            user_agent: ActiveValue::set(params.user_agent.clone()),
            payload: ActiveValue::set(params.payload.clone()),
            last_activity: ActiveValue::set(params.last_activity),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(session)
    }
}

impl ActiveModel {
    /// Updates the session's last activity timestamp
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_last_activity(
        mut self,
        db: &DatabaseConnection,
        timestamp: i32,
    ) -> ModelResult<Model> {
        self.last_activity = ActiveValue::set(timestamp);
        Ok(self.update(db).await?)
    }

    /// Updates the session's payload
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_payload(
        mut self,
        db: &DatabaseConnection,
        payload: String,
    ) -> ModelResult<Model> {
        self.payload = ActiveValue::set(payload);
        Ok(self.update(db).await?)
    }
}
